<script setup>
    import { ref, watch, onMounted, onUnmounted, computed } from 'vue';
    import { ElLoading, ElMessage } from 'element-plus';
    import { useRouter, useRoute } from 'vue-router'
    import request from '../../request/axios';
    import { classifyMessages } from "../../utils/index.js";
    import { projectBaseData } from '../../utils/comData.js'
    import { emitter } from '../../utils/eventBus.js'

    const route = useRoute() // 获取路由对象
    const currentPath = route.path
    const router = useRouter()
    // 收起/展示
    const exhibitionShow = ref(true);

    // 添加计算未读数的方法
    const messageList = ref([])
    const unreadCount = ref(0)
    watch(
        () => projectBaseData.messageNum,
        (newNum) => {
            unreadCount.value = projectBaseData.messageNum
        },
        { immediate: true } // 立即执行一次
    )
    // 消息列表
    const getMessageList = async () => {
        try {
            const res = await request.getV2({ url: 'v1/api-msg-list?page=1&pageNum=99&status=1' });
            messageList.value = res.data.list || [];
            unreadCount.value = res.data.list.reduce((count, message) => {
                return message.notice_status == 1 ? count + 1 : count
            }, 0) || projectBaseData.messageNum;
            console.log(unreadCount.value);

        } catch (error) {
            console.log(error);
        }
    }

    // 历史记录 S
    const historyChat = ref([])
    const getChatRecordList = async () => {
        try {
            const res = await request.getV2({ url: '/v1/api-chat-list' });
            historyChat.value = classifyMessages(res.data)
        } catch (error) {
            console.log(error);
        }
    }
    getChatRecordList()
    // 历史记录 E

    // 用户信息
    const userInfo = ref({})
    const getUserMessage = async () => {
        getMessageList(); // 消息列表
        try {
            const res = await request.getV2({ url: '/v1/api-user-Info' });
            localStorage.setItem("userInfo", JSON.stringify(res.data))
            userInfo.value = res.data
            if (userInfo.value.head == '' || userInfo.value.head == null) {
                userInfo.value.head = new URL(`../../assets/image/icon/user.png`, import.meta.url).href
            }
        } catch (error) {
            console.log(error);
        }
    }
    getUserMessage()

    // 监听路由参数变化
    const menuList = ['/', '/share']
    const isMenu = ref(!menuList.includes(route.path))
    watch(
        () => route.path,
        (newPath, oldPath) => {
            console.log(newPath, oldPath);

            isMenu.value = !menuList.includes(route.path)
            if (route.path === '/share') {
                isMenu.value = route.query.type === '2'
            }
            setTimeout(() => {
                getUserMessage()
                getChatRecordList()
            }, 1000 * 5);
        }
    )

    // 监听缓存里的用户信息变化
    watch(
        () => localStorage.getItem("userInfo"),
        (newPath, oldPath) => {
            getUserMessage()
            getChatRecordList()
        }
    )

    // 点击选中 历史记录 S
    const historyInx = ref(-1)
    const clickHistory = (id) => {
        historyInx.value = id
        localStorage.removeItem("knowledgeId")
        localStorage.removeItem('databaseName')
        router.push('/chatBot?id=' + id)
    }
    // 点击选中 历史记录 E

    onMounted(() => {
        window.addEventListener('storage', handleStorageChange);
        if (!localStorage.getItem("token")) {
            const menuList = ['/authLogin', '/share', '/', '/share']
            // const index = ['/']
            // if (index.includes(route.path)) return
            if (menuList.includes(route.path)) return
            router.push('/')
        }
    });

    onUnmounted(() => {
        window.removeEventListener('storage', handleStorageChange);
    });

    const handleStorageChange = (event) => {
        if (event.key === 'token') {
            if (event.newValue) {
                getUserMessage(); // 更新用户信息
                getChatRecordList(); // 重新获取聊天记录
            }
        }
    };

    // 监听 localStorage 中的 token 变化
    watch(
        () => localStorage.getItem("token"),
        (newValue, oldValue) => {
            if (newValue !== oldValue) {
                getUserMessage(); // 更新用户信息
                getChatRecordList(); // 重新获取聊天记录
            }
        },
        { immediate: true }
    );

    // 跳转知识库
    const goKnowledge = async () => {
        // ElMessage.warning('知识库相关功能正在开发中，敬请期待')
        // return
        try {
            const res = await request.postV2({ url: '/v1/api-user-prompt' })
            if (res.code == 200) {
                if (res.data.is_prompt_status == 1) return ElMessage.warning(res.data.prompt)
                router.push({ name: 'repository' })
                emitter.emit('refresh-repository')
            }
        } catch (error) {
            console.log(error)
        }
    }

</script>

<template>
    <div v-if="isMenu">
        <!-- 展开样式 -->
        <div class="content-menu" v-if="exhibitionShow">
            <el-button class="new-chat" @click="() => router.push('/initialization')"><img
                    src="../../assets/image/icon/new-chat.png" /> 开启新对话</el-button>

            <el-button class="new-chat knowledge-base" @click="goKnowledge"><img
                    src="../../assets/image/icon/knowledge.png" />知识库</el-button>

            <el-button class="new-chat collection" @click="() => router.push('/collection')"><img
                    src="../../assets/image/icon/collection.png" />收藏</el-button>

            <div class="chat-history-list overflow-none">
                <div class="day-list" v-for="(item, index) in historyChat" :key="index">
                    <div class="day-title">{{ item.title }}</div>
                    <div class="day-content">
                        <div :class="['day-content-item', val.id == historyId ? 'active' : '']"
                            v-for="(val, idx) in item.children" :key="idx" @click="clickHistory(val.id)">
                            <img src="../../assets/image/icon/collection-icon.png" v-if="val.knowledge_id"
                                class="knowledge-icon" />
                            <div class="content-name nowrap-hide"> {{val.name}}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="user-content">
                <span class="message-num" v-if="unreadCount > 0">{{unreadCount}}</span>
                <img style="width: 40px; height: 40px;border-radius: 50%" @click="() => router.push('/userInfo')"
                    :src="userInfo.head" />
                <span class="nowrap-hide" @click="() => router.push('/userInfo')">{{userInfo.nickname}}</span>
                <div class="icon-list">
                    <img src="../../assets/image/icon/settings.png" @click="() => router.push('/settings')" />
                    <img src="../../assets/image/icon/small.png" @click="exhibitionShow = !exhibitionShow" />
                </div>
            </div>
        </div>
        <!-- 收起样式 -->
        <div class="content-menu closed-menu" v-else>
            <img src="../../assets/image/icon/model-image.png" style="width: 40px; height: 40px;border-radius: 50%" />
            <img src="../../assets/image/icon/xiao-chat.png" @click="() => router.push('/initialization')" />
            <img src="../../assets/image/icon/xiao-knowledge.png" @click="goKnowledge" />
            <img src="../../assets/image/icon/xiao-collection.png" @click="() => router.push('/collection')" />
            <img src="../../assets/image/icon/small-drop.png" @click="exhibitionShow = !exhibitionShow" />
            <div class="user-content">
                <img src="../../assets/image/icon/settings.png" @click="() => router.push('/settings')" />
                <img :src="userInfo.head" @click="() => router.push('/userInfo')"
                    style="width: 40px; height: 40px;border-radius: 50%" />
            </div>
        </div>
    </div>
</template>

<style scoped lang="scss">
    .message-num {
        position: absolute;
        width: 18px !important;
        height: 18px;
        border-radius: 50%;
        background: red;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px !important;
        color: #fff !important;
        top: 0;
        right: 40px;
    }

    .content-name {
        width: 100%;
        flex: 1;
    }

    .knowledge-icon {
        width: 18px;
        height: 18px;
        margin-right: 4px;
    }

    .content-menu {
        width: 220px;
        height: 100vh;
        overflow: hidden;
        text-align: center;
        background-color: #FAFBFF;
        box-shadow: 0px 0px 20px 0px rgba(23, 95, 170, 0.1);

        .new-chat {
            width: 160px;
            height: 38px;
            border-radius: 12px;
            color: #2D66B3;
            font-size: 16px;
            margin: 30px auto 20px;
            display: flex;
            align-items: center;
            background: rgba(45, 102, 179, 0.1);

            img {
                width: 18px;
                height: 18px;
                margin-right: 4px;
            }
        }

        button:focus,
        button:focus-visible {
            outline: none;
        }

        .collection,
        .knowledge-base {
            color: #000;
            margin-top: 0px;
            border: 1px solid #000;
            background: rgba(255, 255, 255, 0.1);
        }

        .chat-history-list {
            height: calc(100vh - 300px);
            overflow: hidden;
            overflow-y: auto;

            .day-list {
                text-align: left;
                padding: 0 12px;
                margin-bottom: 20px;

                .day-title {
                    color: #999999;
                    font-size: 14px;
                    margin-bottom: 6px;
                }

                .day-content-item {
                    height: 36px;
                    color: #000;
                    font-size: 14px;
                    line-height: 36px;
                    padding-left: 10px;
                    border-radius: 12px;
                    margin: 2px 0;
                    cursor: pointer;
                    display: flex;
                    align-items: center;

                    &:hover {
                        background: rgba(45, 102, 179, 0.1);
                    }
                }

                .active {

                    background: rgba(45, 102, 179, 0.1);
                }
            }
        }

        .user-content {
            display: flex;
            align-items: center;
            padding: 0 16px;
            margin-top: 20px;
            position: relative;

            span {
                width: 80px;
                font-size: 16px;
                color: #3D3D3D;
                margin-left: 8px;
                text-align: left;
                cursor: pointer;
            }

            img {
                cursor: pointer;
            }

            .icon-list {
                display: flex;
                align-items: center;

                img {
                    cursor: pointer;
                    margin: 0 4px;
                }
            }
        }
    }

    .closed-menu {
        width: 70px;
        text-align: center;
        display: flex;
        flex-direction: column;
        flex-wrap: nowrap;
        align-items: center;
        position: relative;

        img {
            width: 24px;
            margin-top: 20px;
            cursor: pointer;
        }

        .user-content {
            display: flex;
            flex-direction: column;
            flex-wrap: nowrap;
            align-items: center;
            position: absolute;
            bottom: 20px;

        }
    }
</style>